package com.webserver.http;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 当前类定义所有HTTP协议规定内容,以便重用
 */
public class HttpContext {
    /**
     * 回车符
     */
    public static final char CR = 13;
    /**
     * 换行符
     */
    public static final char LF = 10;
    private static Map<String, String> mimeMapping = new HashMap<>();

    static {
        initMimeMappion();
    }

    private static void initMimeMappion() {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read("./config/web.xml");
            Element root = doc.getRootElement();
            List<Element> list = root.elements("mime-mapping");
            for (Element empEle : list) {
                String k = empEle.elementText("extension");
                String v = empEle.elementText("mime-type");


                mimeMapping.put(k, v);
            }
            System.out.println("初始化了Content-Type:" + mimeMapping.size() + "个");

        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        System.out.println(getMimeType("png"));
    }

    /**
     * 根据资源的后缀名获取对应的Content-Type的值
     *
     * @param ext
     * @return
     */
    public static String getMimeType(String ext) {
        return mimeMapping.get(ext);
    }
}
